import * as https from 'https'
import * as fs from 'fs'

/**
 * 从URL下载文件内容
 * @param url 远程链接
 * @param outputPath 输出文件路径
 * @param callback 读取完成回调
 * @returns 
 */
export function fetchRemoteFile(url:string, outputPath?:string, callback?:(text:string) => void) {
    return new Promise((resolve, reject) => {
      https.get(url, (response) => {
        if (response.statusCode !== 200) {
          return reject(new Error(`请求失败，状态码: ${response.statusCode}`));
        }

        response.setEncoding('utf8');
        
        if(outputPath) {
            const fileStream = fs.createWriteStream(outputPath);
            response.pipe(fileStream);
            
            fileStream.on('finish', () => {
            fileStream.close();
                resolve(outputPath);
            });
        }

        if(callback) {
            callback(response.setEncoding('utf8').read())
        }
        
        }).on('error', (err) => {
            reject(err);
      });
    });
  }